<template>
<div>
	<Card  dis-hover>
		<p slot="title">优惠券管理</p>
		<div pd2>
			<p>
				<Button size="small" @click="handleShowCreateModal(null)">新增优惠券</Button>
			</p>
			<AutoTable :ref="tableRef" action="/api/services/app/Coupon/AdminSearch" :columns="columns" :query="query" :buttons="buttons" mgt1></AutoTable>
		</div>
	</Card>

	<Modal v-model="showModal" :title="this.model.id?'编辑优惠券':'添加优惠券'" :mask-closable="false">
		<Tabs size="small" v-model="tabName">
			<TabPane label="基本信息" name="info"></TabPane>
			<TabPane :label="`指定商品 (${model.appliedCommodityIds.length})`" name="commodities" :disabled="model.targetType==0"></TabPane>
		</Tabs>
		<div v-show="tabName=='info'">
			<Form :ref="formRef" :model="model" :label-width="100">
				<FormItem label="券名称" prop="name" required>
					<Input v-model="model.name" />
				</FormItem>
				<FormItem label="抵消金额" prop="amount" required>
					<InputNumber v-model="model.amount" :min="0" />
				</FormItem>
				<FormItem label="使用条件" prop="minAmount" required>
					<p>订单金额满 <InputNumber v-model="model.minAmount" :min="0" /> 元</p>
				</FormItem>
				<FormItem label="活动时间" prop="begin">
					<custom-daterange-picker :model="model" beginProp="begin" endProp="end" long></custom-daterange-picker>
				</FormItem>
				<FormItem label="剩余券数量" prop="restCount">
					<InputNumber v-model="model.restCount" :min="0" />
				</FormItem>
				<FormItem prop="isInfinite">
					<Checkbox v-model="model.isInfinite" :min="0">无限券数</Checkbox>
				</FormItem>
				<FormItem label="活动商品" prop="targetType">
					<RadioGroup v-model="model.targetType">
						<Radio :label="0">全部商品</Radio>
						<Radio :label="1">部分商品</Radio>
					</RadioGroup>
				</FormItem>
			</Form>
		</div>
		<div v-show="tabName=='commodities'">
			<commodity-select-list :model="model"></commodity-select-list>
		</div>
		
        <div slot="footer">
            <Button type="primary" @click="handleSave">{{this.model.id?'更新':'保存'}}</Button>
            <Button @click="showModal=false">取消</Button>
        </div>
	</Modal>

	<
</div>
</template>

<script lang="ts">
import { Component, Vue,Inject, Prop,Watch } from 'vue-property-decorator';
import AbpBase from '../../../lib/abpbase';
import AutoTable from "@common/components/AutoTable.vue";
import CustomDaterangePicker from '../../../components/common/custom-daterange-picker.vue'
import CommoditySelectList from '../../../components/common/commodity-select-list.vue'

@Component({
	components:{ AutoTable, CustomDaterangePicker, CommoditySelectList }
})
export default class CouponManager extends AbpBase {
	tabName:string = 'info';
	showModal:boolean=false;
	editModalShow:boolean=false;
	tableRef:string = this.getRandomRef('table')
	formRef:string = this.getRandomRef('form')
	model:any = this.getDefaultModel()
	getDefaultModel() {
		return {
			name: "",
			amount: 0,
			appliedCommodityIds: [],
			minAmount: 0,
			minCount: 0,
			begin: new Date().toString(),
			end: new Date().toString(),
			targetType: 0,
			restCount: 0,
			isInfinite: false
		}
	}
	get buttons() {
		return ['search','search_all']
	}
	get query() {
		return { // 查询条件
			status: { type: "select", label: "状态:", default: 'all', placeholder: "未选择", options: [
					{ value: 'all', label: "所有" },
					{ value: 'notbegin', label: "未开始" },
					{ value: 'ongoing', label: "进行中" },
					{ value: 'ended', label: "已结束" }
			] },
		};
	}
	get columns() {
		return [
			{
				title: '券名称', align: 'center', key: 'name'
			},
			{
				title: '使用条件', align: 'center', render: (h, params) => {
					return h('div', `满${params.row.minAmount}减${params.row.amount}`);
				}
			},
			{
				title: '活动时间', align: 'center', width: 170, render: (h, params) => {
					return h('div', `${this.formatTimeStr(params.row.begin, 'YYYY-MM-DD')} 至 ${this.formatTimeStr(params.row.end, 'YYYY-MM-DD')}`);
				}
			},
			{
				title: '活动商品', align: 'center', width: 75, render: (h, params) => {
					return h('div', ['全部商品', '部分商品'][params.row.targetType]);
				}
			},
			{
				title: '剩余券数', align: 'center', width: 75, render: (h, params) => {
					return h('div', params.row.isInfinite ? '无限' : params.row.restCount);
				}
			},
			{
				title: '已领取券数', align: 'center', width: 100, key: 'grantedCount'
			},
			{
				title: '已使用券数', align: 'center', width: 100, key: 'usedCount'
			},
			{
				title: '活动状态', align: 'center', width: 100, render: (h, params) => {
					var now = new Date();
					var begin = new Date(params.row.begin);
					var end = new Date(params.row.end);
					if(now < begin) {
						return h('div', '未开始');
					}else if(now > end) {
						return h('div', '已结束');
					}else {
						return h('div', '进行中');
					}
				}
			},
			// {
			// 	title: '券领用记录', align: 'center', width: 100, render: (h, params) => {
			// 		return h('span', {
			// 			attrs: { linkable: true, blue: true },
			// 			on: { click: () => {} } 
			// 		}, '查看领用记录');
			// 	}
			// },
			{
				title: '操作', key: 'action', align: 'center', width: 120, render: (h, params) => {
					return h('div', [
						h('Button', {
							props: { type: 'primary', size: 'small' },
							style: { marginRight: '5px' },
							on: { click: () => {
								this.handleShowCreateModal(params.row)
							} }
						}, '编辑'),
						h('Button', {
							props: { type: 'error', size: 'small' },
							style: { marginRight: '5px' },
							on: { click: () => {
								this.handleDelete(params.row.id);
							} }
						}, '删除')
					]);
				}
			}
		]
	}
	handleDelete(id:Number) {
		this.confirm('确认删除该优惠券吗？', async () => {
			var response = await this.post('Coupon/Delete', { id: id });
			if(response.success) {
				this.getpage();
			}
		});
	}
	async handleDeleteBatch() {
		(this.$refs[this.tableRef] as any).handleBatch(async (selectedItems) => {
			this.confirm(`确认要删除选中的${selectedItems.length}优惠券吗`, async () => {
				var ids = selectedItems.map(elem => elem.id);
				var response = await this.post('Coupon/Delete', { ids: ids });
				if(response.success) {
					this.getpage();
				}
			});
		});
	}
	handleShowCreateModal(item) {
		this.tabName = 'info';
		if(item == null) {
			this.model = this.getDefaultModel();
		}else {
			this.model = Object.assign({}, item);
		}
		this.showModal = true;
	}
	handleSave() {
		this.validate( this.formRef, async () => {
			if(!this.model.id) {
				var response = await this.post('Coupon/Create', this.model);
				if(response.success) {
					this.showModal = false;
					this.getpage();
				}
			}else {
				var response = await this.put('Coupon/Update', this.model);
				if(response.success) {
					this.showModal = false;
					this.getpage();
				}
			}
		});
	}
	// async handleChangeEnabled(id, value) {
	// 	if(value == true) {
	// 		await this.post('Coupon/Enabled', { id: id });
	// 	}else {
	// 		await this.post('Coupon/Disabled', { id: id });
	// 	}
	// }
	getpage() {
		(this.$refs[this.tableRef] as any).getData();
	}
}
</script>